﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using CATLTempUpdate.CommonLib;
using System.Threading;
using System.Net.Sockets;
using System.Net;
using CATLTempUpdate.TcpServer;

namespace CATLTempUpdate
{
    public partial class FormCATLTempManageSystem : Form
    {
        [DllImport("controlcan.dll")]
        static extern UInt32 VCI_OpenDevice(UInt32 DeviceType, UInt32 DeviceInd, UInt32 Reserved);
        [DllImport("controlcan.dll")]
        static extern UInt32 VCI_CloseDevice(UInt32 DeviceType, UInt32 DeviceInd);
        [DllImport("controlcan.dll")]
        static extern UInt32 VCI_InitCAN(UInt32 DeviceType, UInt32 DeviceInd, UInt32 CANInd, ref VCI_INIT_CONFIG pInitConfig);
        [DllImport("controlcan.dll")]
        static extern UInt32 VCI_ReadBoardInfo(UInt32 DeviceType, UInt32 DeviceInd, ref VCI_BOARD_INFO pInfo);
        [DllImport("controlcan.dll")]
        static extern UInt32 VCI_ReadErrInfo(UInt32 DeviceType, UInt32 DeviceInd, UInt32 CANInd, ref VCI_ERR_INFO pErrInfo);
        [DllImport("controlcan.dll")]
        static extern UInt32 VCI_ReadCANStatus(UInt32 DeviceType, UInt32 DeviceInd, UInt32 CANInd, ref VCI_CAN_STATUS pCANStatus);

        [DllImport("controlcan.dll")]
        static extern UInt32 VCI_GetReference(UInt32 DeviceType, UInt32 DeviceInd, UInt32 CANInd, UInt32 RefType, ref byte pData);
        [DllImport("controlcan.dll")]
        static extern UInt32 VCI_SetReference(UInt32 DeviceType, UInt32 DeviceInd, UInt32 CANInd, UInt32 RefType, ref byte pData);

        [DllImport("controlcan.dll")]
        unsafe static extern UInt32 VCI_GetReceiveNum(UInt32 DeviceType, UInt32 DeviceInd, UInt32 CANInd);
        [DllImport("controlcan.dll")]
        static extern UInt32 VCI_ClearBuffer(UInt32 DeviceType, UInt32 DeviceInd, UInt32 CANInd);

        [DllImport("controlcan.dll")]
        static extern UInt32 VCI_StartCAN(UInt32 DeviceType, UInt32 DeviceInd, UInt32 CANInd);
        [DllImport("controlcan.dll")]
        static extern UInt32 VCI_ResetCAN(UInt32 DeviceType, UInt32 DeviceInd, UInt32 CANInd);

        [DllImport("controlcan.dll")]
        static extern UInt32 VCI_Transmit(UInt32 DeviceType, UInt32 DeviceInd, UInt32 CANInd, ref VCI_CAN_OBJ pSend, UInt32 Len);
        //[DllImport("controlcan.dll")]
        //static extern UInt32 VCI_Receive(UInt32 DeviceType, UInt32 DeviceInd, UInt32 CANInd, ref VCI_CAN_OBJ pReceive, UInt32 Len, Int32 WaitTime);
        [DllImport("controlcan.dll")]
        unsafe static extern UInt32 VCI_Receive(UInt32 DeviceType, UInt32 DeviceInd, UInt32 CANInd, VCI_CAN_OBJ* pReceive, UInt32 Len, Int32 WaitTime);

        //static UInt32 m_devtype = 4;//USBCAN2
        //static UInt32 m_devtype = (UInt32)can.DEV_TYPE.VCI_USBCAN1;//CANNETE
        static UInt32 m_devtype = (UInt32)can.DEV_TYPE.VCI_CANETTCP;//CANNETE

        UInt32 m_bOpen = 0;
        UInt32 m_devind = 0;
        UInt32 m_canind = 0;

        UInt32 m_bOpen2 = 0;
        UInt32 m_devind2 = 0;
        UInt32 m_canind2 = 0;

        //TempCan3
        UInt32 m_bOpen3 = 0;
        UInt32 m_devind3 = 0;
        UInt32 m_canind3 = 0;

        VCI_CAN_OBJ[] m_recobj = new VCI_CAN_OBJ[50];
        VCI_CAN_OBJ[] m_recobj2 = new VCI_CAN_OBJ[50];
        VCI_CAN_OBJ[] m_recobj3 = new VCI_CAN_OBJ[50];

        //PLCUpdateBLL plcUB = new PLCUpdateBLL();
        int MinNo = 0;
        int MaxNo = 100;
        public static bool ClearToken = false;
        
        TcpReciveAndSend Readyte;
        bool wantExit=false;

        //初始化之前通道对应关系dict
        Dictionary<int, int> OldSeq = new Dictionary<int, int>();

        //初始化当前通道对应关系dict

        Dictionary<int, int> NewSeq = new Dictionary<int, int>();


        //初始化通道对应关系list
        List<int> can1chseq = new List<int>();
        int columnno = 7;
        int rowno = 1;
        int chno = 10;
        public static double outtemp=0;

        void InitRecObj()
        {
            for (int i = 0; i < m_recobj.Length;i++ )
            {
                m_recobj[i].Init();
            }
        }

        public FormCATLTempManageSystem()
        {
            InitializeComponent();
            TempCanData.TempDt.Columns.Add("chno", typeof(int));
            TempCanData.TempDt.Columns.Add("temp", typeof(float));
            for (int i = 0; i < 24; i++)
            {
                DataRow dr = TempCanData.TempDt.NewRow();
                dr["chno"] = (i + 1);
                dr["temp"] = 10;
                TempCanData.TempDt.Rows.Add(dr);
            }
            InitialCanSeqList();
            bgWriteLog.RunWorkerAsync();
            bgInitialServer.RunWorkerAsync();

            InitRecObj();
            checkbuttonenable();

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            
            //ThreadPool.SetMaxThreads(100, 200);
            //ThreadPool.SetMinThreads(2, 40);
            //for (int i = MinNo; i < MaxNo; i++)
            //{
            //    ThreadPool.QueueUserWorkItem(
            //    new WaitCallback(test),i);
            //}
            
            //Convert.to

        }

        public  void test(Object str)
        {
            Thread.Sleep(1000);
            //if (MinNo < MaxNo)
            //{
            //    MinNo++;
            //}
            int workthreadnumber;
            int iothreadnumber;
            ThreadPool.GetAvailableThreads(out workthreadnumber, out iothreadnumber);
            Console.WriteLine("CurrentThreadNo:"+ str.ToString() + ",WorkThread NO："+ workthreadnumber+",IO ThreadNo:"+iothreadnumber);
        }

        private void minform()
        {

            this.KeyPreview = true;
            this.Visible = false;
            this.ShowInTaskbar = false;  //不显示在系统任务栏 
            notifyIcon1.Visible = true;  //托盘图标可见
            this.notifyIcon1.ShowBalloonTip(3, "提示", "系统仍在运行！\n如要打开，请双击图标", ToolTipIcon.Info);

        }
        private void Initializenotifyicon()
        {
            //定义一个MenuItem数组，并把此数组同时赋值给ContextMenu对象 
            MenuItem[] mnuItms = new MenuItem[7];
            mnuItms[0] = new MenuItem();
            mnuItms[0].Text = "显示窗口";
            mnuItms[0].Click += new System.EventHandler(this.notifyIcon1_showfrom);

            ContextMenu notifyiconMnu = new ContextMenu(mnuItms);
            notifyIcon1.ContextMenu = notifyiconMnu;
            //为托盘程序加入设定好的ContextMenu对象 
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (this.WindowState == FormWindowState.Normal)
            {
                this.WindowState = FormWindowState.Minimized;

                this.Hide();
            }
            else if (this.WindowState == FormWindowState.Minimized)
            {
                this.Show();
                this.WindowState = FormWindowState.Normal;
                this.Activate();
            }

        }
        public void notifyIcon1_showfrom(object sender, System.EventArgs e)
        {

            this.ShowInTaskbar = true;
            this.WindowState = FormWindowState.Normal;
            notifyIcon1.Visible = false;
        }

        private void Form1_SizeChanged(object sender, EventArgs e)
        {

            this.ShowInTaskbar = false;  //不显示在系统任务栏 
            notifyIcon1.Visible = true;  //托盘图标可见 
            this.notifyIcon1.ShowBalloonTip(3, "提示", "系统仍在运行！\n如要打开，请双击图标", ToolTipIcon.Info);
        }

        
        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            Application.Exit();
        }
        /// <summary>
        /// 整型数转字节数组
        /// </summary>
        /// <param name="b"></param>
        /// <returns></returns>
        public static UInt64 BytesToInt(byte[] b)
        {
            UInt64 mask = 0xff;
            UInt64 temp = 0;
            UInt64 res = 0;
            for (int i = 0; i < b.Length; i++)
            {
                res <<= 8;
                temp = b[i] & mask;
                res |= temp;
            }
            return res;
        }

        /// <summary>
        /// 字节数组转整型数
        /// </summary>
        /// <param name="num"></param>
        /// <param name="bits">位数，对于整形数的所占位数</param>
        /// <returns></returns>
        public static byte[] IntToBytes(UInt64 num, int bits)
        {
            byte[] b = new byte[bits];
            for (int i = 0; i < bits; i++)
            {
                //b[i] = (byte)(num >> ((bits - 1) * 8 - i * 8));//高字节在索引低处
                b[i] = (byte)((num >> (i * 8)) & 0xff);

            }
            return b;
        }

        private unsafe void Can1RecFunc()
        {
            UInt32 res = new UInt32();
            res = VCI_GetReceiveNum(m_devtype, m_devind, m_canind);
            if (res == 0)
                return;
            //VCI_CAN_OBJ* pobj= new ;//= new VCI_CAN_OBJ[50];
            fixed (VCI_CAN_OBJ* pobj = &m_recobj[0])
            {
                res = VCI_Receive(m_devtype, m_devind, m_canind, pobj, 50/*50*/, 50);
            }

            StringBuilder sb = new StringBuilder("");
            string tempVal = "";
            for (UInt32 i = 0; i < res; i++)
            {
                string canid = System.Convert.ToString((Int32)m_recobj[i].ID, 16);


                string endtagstr = canid.Substring(canid.Length - 2, 2);
                int stageIndex = Convert.ToInt32(endtagstr, 16) - 100;
                int rowindex = stageIndex % 4;
                if (rowindex == 0)
                {
                    rowindex = 4;
                }
                rowindex = 5 - rowindex;
                int colindex = ((stageIndex - 1) / 4) + 1;


                sb.Append("接收到数据: ");
                sb.Append("帧ID:0x" + canid);

                if (m_recobj[i].RemoteFlag == 0 && (m_recobj[i].ID & 0x00ff0000) == 0x00310000)
                {
                    sb.Append(" 数据: ");
                    byte len = (byte)(m_recobj[i].DataLen % 9);
                    byte j = 0;

                    byte[] tempdata = new byte[8];
                    fixed (byte* bdata = m_recobj[i].Data)
                    {
                        if (j++ < len)
                            sb.Append(" " + System.Convert.ToString(bdata[0], 16));
                        tempdata[0] = bdata[0];
                        if (j++ < len)
                            sb.Append(" " + System.Convert.ToString(bdata[1], 16));
                        tempdata[1] = bdata[1];

                        if (tempdata[1] != 0x18)
                        {
                            return;
                        }

                        if (j++ < len)
                            sb.Append(" " + System.Convert.ToString(bdata[2], 16));
                        tempdata[3] = bdata[2];
                        if (j++ < len)
                            sb.Append(" " + System.Convert.ToString(bdata[3], 16));
                        tempdata[2] = bdata[3];
                        if (j++ < len)
                            sb.Append(" " + System.Convert.ToString(bdata[4], 16));
                        tempdata[5] = bdata[4];
                        if (j++ < len)
                            sb.Append(" " + System.Convert.ToString(bdata[5], 16));
                        tempdata[4] = bdata[5];
                        if (j++ < len)
                            sb.Append(" " + System.Convert.ToString(bdata[6], 16));
                        tempdata[7] = bdata[6];
                        if (j++ < len)
                            sb.Append(" " + System.Convert.ToString(bdata[7], 16));
                        tempdata[6] = bdata[7];
                    }
                    int packindex = Convert.ToInt32(tempdata[0]);
                    if (packindex <= 5 || packindex >= 15)
                    {
                        return;
                    }

                    Int16 tempint1 = BitConverter.ToInt16(tempdata, 2);
                    Int16 tempint2 = BitConverter.ToInt16(tempdata, 4);
                    Int16 tempint3 = BitConverter.ToInt16(tempdata, 6);

                    //更新全局温度list
                    //截取温度1，温度2，温度3
                    Byte[] temp1 = new Byte[] { tempdata[3], tempdata[2] };
                    Byte[] temp2 = new Byte[] { tempdata[5], tempdata[4] };
                    Byte[] temp3 = new Byte[] { tempdata[7], tempdata[6] };

                    if ((Convert.ToDecimal(BitConverter.ToInt16(tempdata, 2)) * (decimal)0.1) < 10 || (Convert.ToDecimal(BitConverter.ToInt16(tempdata, 4)) * (decimal)0.1) < 10 || (Convert.ToDecimal(BitConverter.ToInt16(tempdata, 6)) * (decimal)0.1) < 10)
                    {
                        Log.MeasureError.Add("温度<10异常，原始Package为" + sb.ToString());
                    }


                    int chno1 = PackCHIdToChId((packindex * 3 - 2));
                    int chno2 = PackCHIdToChId((packindex * 3 - 1));
                    int chno3 = PackCHIdToChId((packindex * 3));

                    try
                    {
                        if (chno1 >= 1 && chno1 <= 24)
                        {

                            SetTempData(1, colindex, rowindex, NewSeq[chno1], temp1);
                        }
                        if (chno2 >= 1 && chno2 <= 24)
                        {

                            SetTempData(1, colindex, rowindex, NewSeq[chno2], temp2);
                        }
                        if (chno3 >= 1 && chno3 <= 24)
                        {

                            SetTempData(1, colindex, rowindex, NewSeq[chno3], temp3);
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.SystemError.Add("将温度数据更新到List异常,列:" + colindex + " 层号:" + rowindex + " packindex:" + packindex + " chno:" + (packindex * 3 - 2) + "，数据为:" + sb.ToString() + ex.ToString());
                    }


                    tempVal = Convert.ToString(Convert.ToDecimal(BitConverter.ToInt16(tempdata, 2)) * (decimal)0.1);
                    if (canDataViewEable)
                    {
                        sb.Append(" 架台：" + colindex.ToString() + "-" + rowindex.ToString());
                        sb.Append(" 温度值：" + (packindex * 3 - 2).ToString() + "(" + PackCHIdToChId((packindex * 3 - 2)) + ") : " + tempVal);
                        sb.Append(" " + (packindex * 3 - 1).ToString() + "(" + PackCHIdToChId((packindex * 3 - 1)) + ") : " + Convert.ToString(Convert.ToDecimal(BitConverter.ToInt16(tempdata, 4)) * (decimal)0.1));
                        sb.Append(" " + (packindex * 3).ToString() + "(" + PackCHIdToChId((packindex * 3)) + ") : " + Convert.ToString(Convert.ToDecimal(BitConverter.ToInt16(tempdata, 6)) * (decimal)0.1));
                    }

                }
                if (canDataViewEable)
                {
                    listBox_Info.Items.Add(sb.ToString());
                    listBox_Info.SelectedIndex = listBox_Info.Items.Count - 1;
                }
                sb.Clear();

            }
        }

        private unsafe void Can2RecFunc()
        {
            UInt32 res = new UInt32();
            res = VCI_GetReceiveNum(m_devtype, m_devind2, m_canind);
            if (res == 0)
                return;

            //res = VCI_Receive(m_devtype, m_devind, m_canind, ref m_recobj[0],/*50*/1, 100);
            fixed (VCI_CAN_OBJ* pobj = &m_recobj2[0])
            {
                res = VCI_Receive(m_devtype, m_devind2, m_canind, pobj, 50/*50*/, 50);
            }

            String str = "";
            for (UInt32 i = 0; i < res; i++)
            {
                string canid = System.Convert.ToString((Int32)m_recobj2[i].ID, 16);

                string endtagstr = canid.Substring(canid.Length - 2, 2);
                int stageIndex = Convert.ToInt32(endtagstr, 16) - 100 + 16;   //原来的

                int rowindex = stageIndex % 4;
                if (rowindex == 0)
                {
                    rowindex = 4;
                }

                rowindex = 5 - rowindex;
                int colindex = ((stageIndex - 1) / 4) + 1;

                str = "接收到数据: ";
                str += "  帧ID:0x" + canid;

                string tempVal = "";

                if (m_recobj2[i].RemoteFlag == 0 && (m_recobj2[i].ID & 0x00ff0000) == 0x00310000)
                {
                    str += " 数据: ";
                    byte len = (byte)(m_recobj2[i].DataLen % 9);
                    byte j = 0;

                    byte[] tempdata = new byte[8];
                    fixed (byte* bdata = m_recobj2[i].Data)
                    {
                        if (j++ < len)
                            str += " " + System.Convert.ToString(bdata[0], 16);
                        tempdata[0] = bdata[0];
                        if (j++ < len)
                            str += " " + System.Convert.ToString(bdata[1], 16);
                        tempdata[1] = bdata[1];

                        if (tempdata[1] != 0x18)
                        {
                            return;
                        }
                        if (j++ < len)
                            str += " " + System.Convert.ToString(bdata[2], 16);
                        tempdata[3] = bdata[2];
                        if (j++ < len)
                            str += " " + System.Convert.ToString(bdata[3], 16);
                        tempdata[2] = bdata[3];
                        if (j++ < len)
                            str += " " + System.Convert.ToString(bdata[4], 16);
                        tempdata[5] = bdata[4];
                        if (j++ < len)
                            str += " " + System.Convert.ToString(bdata[5], 16);
                        tempdata[4] = bdata[5];
                        if (j++ < len)
                            str += " " + System.Convert.ToString(bdata[6], 16);
                        tempdata[7] = bdata[6];
                        if (j++ < len)
                            str += " " + System.Convert.ToString(bdata[7], 16);
                        tempdata[6] = bdata[7];
                    }
                    int packindex = Convert.ToInt32(tempdata[0]);
                    if (packindex <= 5 || packindex >= 15)
                    {
                        return;
                    }


                    Int16 tempint1 = BitConverter.ToInt16(tempdata, 2);
                    Int16 tempint2 = BitConverter.ToInt16(tempdata, 4);
                    Int16 tempint3 = BitConverter.ToInt16(tempdata, 6);

                    //更新全局温度list
                    //截取温度1，温度2，温度3
                    Byte[] temp1 = new Byte[] { tempdata[3], tempdata[2] };
                    Byte[] temp2 = new Byte[] { tempdata[5], tempdata[4] };
                    Byte[] temp3 = new Byte[] { tempdata[7], tempdata[6] };


                    int chno1 = PackCHIdToChId((packindex * 3 - 2));
                    int chno2 = PackCHIdToChId((packindex * 3 - 1));
                    int chno3 = PackCHIdToChId((packindex * 3));
                    if (Convert.ToDecimal(tempint1 * (decimal)0.1) < 10 || (Convert.ToDecimal(tempint2 * (decimal)0.1)) < 10 || (Convert.ToDecimal(tempint3 * (decimal)0.1)) < 10)
                    {
                        Log.MeasureError.Add("当前温度1为："+tempint1+ "温度2为：" + tempint2+ "温度3为：" + tempint3  + "<10异常，原始Package为" + str);
                    }

                    try
                    {
                        if (chno1 >= 1 && chno1 <= 24)
                        {

                            SetTempData(2, colindex, rowindex, NewSeq[chno1], temp1);
                        }
                        if (chno2 >= 1 && chno2 <= 24)
                        {

                            SetTempData(2, colindex, rowindex, NewSeq[chno2], temp2);
                        }
                        if (chno3 >= 1 && chno3 <= 24)
                        {

                            SetTempData(2, colindex, rowindex, NewSeq[chno3], temp3);
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.SystemError.Add("将温度数据更新到List异常,列:" + colindex + " 层号:" + rowindex + " packindex:" + packindex + " chno:" + (packindex * 3 - 2) + "，数据为:" + str + ex.ToString());
                    }


                    tempVal = Convert.ToString(Convert.ToDecimal(BitConverter.ToInt16(tempdata, 2)) * (decimal)0.1);
                    if (canDataViewEable)
                    {
                        str += " 架台：" + colindex.ToString() + "-" + rowindex.ToString();
                        str += " 温度值：" + (packindex * 3 - 2).ToString() + "(" + PackCHIdToChId((packindex * 3 - 2)) + ") : " + tempVal;
                        str += " " + (packindex * 3 - 1).ToString() + "(" + PackCHIdToChId((packindex * 3 - 1)) + ") : " + Convert.ToString(Convert.ToDecimal(BitConverter.ToInt16(tempdata, 4)) * (decimal)0.1);
                        str += " " + (packindex * 3).ToString() + "(" + PackCHIdToChId((packindex * 3)) + ") : " + Convert.ToString(Convert.ToDecimal(BitConverter.ToInt16(tempdata, 6)) * (decimal)0.1);
                    }
                }
                
                if (canDataViewEable)
                {
                    this.Invoke(new Action(() =>
                    {
                        listBox_Info.Items.Add(str);
                        listBox_Info.SelectedIndex = listBox_Info.Items.Count - 1;
                    }
                       ));

                }

                str = null;

            }
        }

        public static void  ShowData()
        {
            if (canDataViewEable)
            {
                
            }
        }

        private unsafe void Can3RecFunc()
        {

            UInt32 res = new UInt32();
            res = VCI_GetReceiveNum(m_devtype, m_devind3, m_canind);
            if (res == 0)
                return;

            //res = VCI_Receive(m_devtype, m_devind, m_canind, ref m_recobj[0],/*50*/1, 100);
            fixed (VCI_CAN_OBJ* pobj = &m_recobj3[0])
            {
                res = VCI_Receive(m_devtype, m_devind3, m_canind, pobj, 50/*50*/, 50);
            }

            StringBuilder sb = new StringBuilder("");
            for (UInt32 i = 0; i < res; i++)
            {
                string canid = System.Convert.ToString((Int32)m_recobj3[i].ID, 16);

                string endtagstr = canid.Substring(canid.Length - 2, 2);
                int stageIndex = Convert.ToInt32(endtagstr, 16) - 100 + 32;   //原来的

                int rowindex = stageIndex % 4;
                if (rowindex == 0)
                {
                    rowindex = 4;
                }

                rowindex = 5 - rowindex;
                int colindex = ((stageIndex - 1) / 4) + 1;

                sb.Append("接收到Can3数据: ");
                sb.Append("  帧ID:0x" + canid);

                string tempVal = "";

                if (m_recobj3[i].RemoteFlag == 0 && (m_recobj3[i].ID & 0x00ff0000) == 0x00310000)
                {
                    sb.Append(" 数据: ");
                    byte len = (byte)(m_recobj3[i].DataLen % 9);
                    byte j = 0;

                    byte[] tempdata = new byte[8];
                    fixed (byte* bdata = m_recobj3[i].Data)
                    {
                        if (j++ < len)
                            sb.Append(" " + System.Convert.ToString(bdata[0], 16));
                        tempdata[0] = bdata[0];
                        if (j++ < len)
                            sb.Append(" " + System.Convert.ToString(bdata[1], 16));
                        tempdata[1] = bdata[1];

                        if (tempdata[1] != 0x18)
                        {
                            return;
                        }
                        if (j++ < len)
                            sb.Append(" " + System.Convert.ToString(bdata[2], 16));
                        tempdata[3] = bdata[2];
                        if (j++ < len)
                            sb.Append(" " + System.Convert.ToString(bdata[3], 16));
                        tempdata[2] = bdata[3];
                        if (j++ < len)
                            sb.Append(" " + System.Convert.ToString(bdata[4], 16));
                        tempdata[5] = bdata[4];
                        if (j++ < len)
                            sb.Append(" " + System.Convert.ToString(bdata[5], 16));
                        tempdata[4] = bdata[5];
                        if (j++ < len)
                            sb.Append(" " + System.Convert.ToString(bdata[6], 16));
                        tempdata[7] = bdata[6];
                        if (j++ < len)
                            sb.Append(" " + System.Convert.ToString(bdata[7], 16));
                        tempdata[6] = bdata[7];

                        int packindex = Convert.ToInt32(tempdata[0]);
                        if (packindex <= 5 || packindex >= 15)
                        {
                            return;
                        }

                        Int16 tempint1 = BitConverter.ToInt16(tempdata, 2);
                        Int16 tempint2 = BitConverter.ToInt16(tempdata, 4);
                        Int16 tempint3 = BitConverter.ToInt16(tempdata, 6);

                        //更新全局温度list
                        //截取温度1，温度2，温度3
                        Byte[] temp1 = new Byte[] { tempdata[3], tempdata[2] };
                        Byte[] temp2 = new Byte[] { tempdata[5], tempdata[4] };
                        Byte[] temp3 = new Byte[] { tempdata[7], tempdata[6] };

                        if ((Convert.ToDecimal(BitConverter.ToInt16(tempdata, 2)) * (decimal)0.1) < 10 || (Convert.ToDecimal(BitConverter.ToInt16(tempdata, 4)) * (decimal)0.1) < 10 || (Convert.ToDecimal(BitConverter.ToInt16(tempdata, 6)) * (decimal)0.1) < 10)
                        {
                            Log.MeasureError.Add("温度<10度异常，原始Package为" + sb.ToString());
                        }



                        int chno1 = PackCHIdToChId((packindex * 3 - 2));
                        int chno2 = PackCHIdToChId((packindex * 3 - 1));
                        int chno3 = PackCHIdToChId((packindex * 3));

                        try
                        {
                            if (chno1 >= 1 && chno1 <= 24)
                            {

                                SetTempData(3, colindex, rowindex, NewSeq[chno1], temp1);
                            }
                            if (chno2 >= 1 && chno2 <= 24)
                            {

                                SetTempData(3, colindex, rowindex, NewSeq[chno2], temp2);
                            }
                            if (chno3 >= 1 && chno3 <= 24)
                            {

                                SetTempData(3, colindex, rowindex, NewSeq[chno3], temp3);
                            }
                        }
                        catch (Exception ex)
                        {
                            Log.SystemError.Add("将温度数据更新到List异常,列:" + colindex + " 层号:" + rowindex + " packindex:" + packindex + " chno:" + (packindex * 3 - 2) + "，数据为:" + sb.ToString() + ex.ToString());
                        }

                        tempVal = Convert.ToString(Convert.ToDecimal(BitConverter.ToInt16(tempdata, 2)) * (decimal)0.1);
                        if (canDataViewEable)
                        {
                            sb.Append(" 架台：" + colindex.ToString() + "-" + rowindex.ToString());
                            sb.Append(" 温度值：" + (packindex * 3 - 2).ToString() + "(" + PackCHIdToChId((packindex * 3 - 2)) + ") : " + tempVal);
                            sb.Append(" " + (packindex * 3 - 1).ToString() + "(" + PackCHIdToChId((packindex * 3 - 1)) + ") : " + Convert.ToString(Convert.ToDecimal(BitConverter.ToInt16(tempdata, 4)) * (decimal)0.1));
                            sb.Append(" " + (packindex * 3).ToString() + "(" + PackCHIdToChId((packindex * 3)) + ") : " + Convert.ToString(Convert.ToDecimal(BitConverter.ToInt16(tempdata, 6)) * (decimal)0.1));
                        }
                    }
                }
                if (canDataViewEable)
                {
                    this.Invoke(new Action(() =>
                    {
                        listBox_Info.Items.Add(sb.ToString());
                        listBox_Info.SelectedIndex = listBox_Info.Items.Count - 1;
                    }
                       ));

                }
                sb.Clear();

            }
        }

        private void buttonConnect_Click(object sender, EventArgs e)
        {
            FormCATLTempManageSystem.ClearToken = true;
        }

        unsafe private void timer_rec_Tick(object sender, EventArgs e)
        {
            Thread thd1 = new Thread(Can1RecFunc);
            thd1.Start();
            
        }

        private int PackCHIdToChId(int PackCHId)
        {

            //(6 - 14)*3-2
            int Chid = 0;
            int a = (PackCHId-1 - 15)/5;
            int b = PackCHId % 5;
            if (b == 0)
            {
                b = 5;
            }
            b = 6 - b;
            PackCHId = a * 5 + b;
            if (PackCHId > 0 && PackCHId < 13)
            {
                if (PackCHId > 9)
                {
                    Chid = PackCHId - 9 + 18;
                }
                else
                {
                    Chid = PackCHId;
                }
               
            }
            else if (PackCHId > 12 && PackCHId < 25)
            {
                if (PackCHId > 21)
                {
                    Chid = PackCHId - 21 + 21;
                }
                else
                {
                    Chid = (PackCHId - 12) + 9;
                }

            }
            return Chid;
        }


        private int PackIdToChId(int PackCHId)
        {
            //6*3=18
            //    16,17,18,19,20,21
            //(6 - 14)*3-2
            PackCHId = PackCHId - 15;
            int Chid = 0;
            if (PackCHId > 0 && PackCHId < 13)
            {
                if (PackCHId > 9)
                {
                    Chid = PackCHId;
                }
                else
                {
                    Chid = PackCHId;
                }

            }
            else if (PackCHId > 12 && PackCHId < 25)
            {
                if (PackCHId > 21)
                {
                    Chid = PackCHId - 21 + 21;
                }
                else
                {
                    Chid = (PackCHId - 12) + 9;
                }

            }
            return Chid;
        }


        private void button_StartCAN_Click(object sender, EventArgs e)
        {
            string TempData = "7E 01 00 01 02 00 02 00 ";//8F FA 7E";
            TempData += textBox_desport.Text.PadLeft(2, '0');
            byte[] Temparray = strToToHexByte(TempData);
            byte[] TempByteArray = new byte[Temparray.Length + 3];
            for (int i = 0; i < Temparray.Length; i++)
            {
                TempByteArray[i] = Temparray[i];
            }
            //追加CRC
            Int16 crcint = CRCCheck.CRCCode(Temparray, Temparray.Length);
            string arrayVal = Convert.ToString(crcint, 16).ToUpper();//获取数组校验码
            arrayVal = arrayVal.PadLeft(4, '0');
            byte[] crcarray = strToToHexByte(arrayVal);

            TempByteArray[Temparray.Length] = crcarray[1];
            TempByteArray[Temparray.Length + 1] = crcarray[0];
            TempByteArray[Temparray.Length + 2] = 0x7e;
            //AnalysisBytes.sndBytes.Add(TempByteArray);

        }

        private void button_StopCAN_Click(object sender, EventArgs e)
        {
            string TempData = "7E 01 00 "+ textBox_IP .Text.PadLeft(2,'0')+ " 02 00 02 00 ";//8F FA 7E";
            TempData += Convert.ToInt32(textBox_desport.Text).ToString("X").PadLeft(2,'0');
            byte[] Temparray = strToToHexByte(TempData);
            byte[] TempByteArray = new byte[Temparray.Length + 3];
            for (int i = 0; i < Temparray.Length; i++)
            {
                TempByteArray[i] = Temparray[i];
            }
            //追加CRC
            Int16 crcint = CRCCheck.CRCCode(Temparray,Temparray.Length);
            string arrayVal = Convert.ToString(crcint, 16).ToUpper();//获取数组校验码
            arrayVal = arrayVal.PadLeft(4,'0');
            byte[] crcarray = strToToHexByte(arrayVal);

            TempByteArray[Temparray.Length] = crcarray[1];
            TempByteArray[Temparray.Length + 1] = crcarray[0];
            TempByteArray[Temparray.Length + 2] = 0x7e;
            //AnalysisBytes.sndBytes.Add(TempByteArray);

        }

        private static byte[] strToToHexByte(string hexString)
        {
            hexString = hexString.Replace(" ", "");
            if ((hexString.Length % 2) != 0)
                hexString += " ";
            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
            return returnBytes;
        }

        void checkbuttonenable()
        {

            textBox_IP.Enabled = true;
            textBox_desport.Enabled = true;
            textBox_srcport.Enabled = false;



        }
        private void radioButton_tcps_CheckedChanged(object sender, EventArgs e)
        {
            checkbuttonenable();
        }

        private void radioButton_udp_CheckedChanged(object sender, EventArgs e)
        {
            checkbuttonenable();
        }

        private void radioButton_tcpc_CheckedChanged(object sender, EventArgs e)
        {
            checkbuttonenable();
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            TcpReciveAndSend.exit = true;
            wantExit = true;
            if (m_bOpen == 1)
            {
                VCI_CloseDevice(m_devtype, m_devind);
            }
            if (m_bOpen2 == 1)
            {
                VCI_CloseDevice(m_devtype, m_devind2);
            }
            if (m_bOpen3 == 1)
            {
                VCI_CloseDevice(m_devtype, m_devind3);
            }

            //if (MessageBox.Show("确认要关闭温度上传软件吗？这将导致架台无法获取温度信息！", "温度上传", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
            //    != DialogResult.Yes)
            //{
            //    e.Cancel = true;
            //    return;
            //}
        }

        private void listBox_Info_DrawItem(object sender, DrawItemEventArgs e)
        {
            if (listBox_Info.Items.Count > 200)
            {
                listBox_Info.Items.RemoveAt(0);
            }
        }


        

        


        
        
        private void Form1_SizeChanged_1(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.Hide(); //或者是this.Visible = false;
                this.notifyIcon1.Visible = true;
            }

        }

        
        
        private void buttonConnect2_Click(object sender, EventArgs e)
        {
            if (m_bOpen2 == 1)
            {
                VCI_CloseDevice(m_devtype, m_devind2);
                m_bOpen2 = 0;
            }
            else
            {
                uint srcport = 0;

                m_devtype = (UInt32)can.DEV_TYPE.VCI_CANETTCP;//


                m_devind2 = (UInt32)1;
                m_canind2 = 0;// (UInt32)comboBox_CANIndex.SelectedIndex;

                if (VCI_OpenDevice(m_devtype, m_devind2, srcport) == 0)
                {
                    MessageBox.Show("打开设备失败,请检查设备类型和设备索引号是否正确", "错误",
                            MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }

                //m_bOpen = 1;
                //VCI_INIT_CONFIG config = new VCI_INIT_CONFIG();
                //config.AccCode = System.Convert.ToUInt32("0x" + textBox_AccCode.Text, 16);
                //config.AccMask = System.Convert.ToUInt32("0x" + textBox_AccMask.Text, 16);
                //config.Timing0 = System.Convert.ToByte("0x" + textBox_Time0.Text, 16);
                //config.Timing1 = System.Convert.ToByte("0x" + textBox_Time1.Text, 16);
                //config.Filter = (Byte)comboBox_Filter.SelectedIndex;
                //config.Mode = (Byte)comboBox_Mode.SelectedIndex;
                //VCI_InitCAN(m_devtype, m_devind, m_canind, ref config);

                //////////////////////////////////////////////////////////////////////////

                //
                string pip = tbxIP2.Text;
                char[] chars = pip.ToCharArray();
                byte[] bs = new byte[50];
                for (int i = 0; i < chars.Length; i++)
                {
                    bs[i] = (byte)chars[i];
                }
                uint cmdtype = (uint)can.CMD.CMD_DESIP;
                if ((uint)can.STATUS.STATUS_OK != VCI_SetReference(m_devtype, m_devind2, m_canind2, cmdtype, ref bs[0]))
                {
                    MessageBox.Show("设置目标IP出错 failed");
                    return;
                }
                //
                uint desport = Convert.ToUInt32(textBox_desport2.Text);
                byte[] desports = IntToBytes(desport, 4);
                cmdtype = (uint)can.CMD.CMD_DESPORT;
                if ((uint)can.STATUS.STATUS_OK != VCI_SetReference(m_devtype, m_devind2, m_canind2, cmdtype, ref desports[0]))
                {
                    MessageBox.Show("设置目标端口出错 failed");
                    return;
                }
                //

                cmdtype = (uint)can.CMD.CMD_TCP_TYPE;
                uint tcptype = (uint)can.TCPTYPE.TCP_CLIENT;
                byte[] types = IntToBytes(tcptype, 4);
                if ((uint)can.STATUS.STATUS_OK != VCI_SetReference(m_devtype, m_devind2, m_canind2, cmdtype, ref types[0]))
                {
                    MessageBox.Show("设置TCP工作方式出错 failed");
                    return;
                }



                m_bOpen2 = 1;
            }
            buttonConnect2.Text = m_bOpen2 == 1 ? "断开" : "连接";
            timer_rec2.Enabled = m_bOpen2 == 1 ? true : false;
            //if (m_bOpen2 == 1)
            //{
            //    bgw_rec2.RunWorkerAsync();
            //}
        }

        private void button_StartCAN2_Click(object sender, EventArgs e)
        {
            if (m_bOpen2 == 0)
                return;
            if (1 != VCI_StartCAN(m_devtype, m_devind2, m_canind2))
            {
                MessageBox.Show("CAN-2启动失败", "错误", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            listBox_Info.Items.Add("CAN-2启动成功");
            listBox_Info.SelectedIndex = listBox_Info.Items.Count - 1;
        }

        private void button_StopCAN2_Click(object sender, EventArgs e)
        {
            if (m_bOpen2 == 0)
                return;
            VCI_ResetCAN(m_devtype, m_devind2, m_canind);
        }

        unsafe private void timer_rec2_Tick(object sender, EventArgs e)
        {
            Thread thd2 = new Thread(Can2RecFunc);
            thd2.Start();
        }

        private void listBox_Info_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        public static bool canDataViewEable = false;
        private void chkDataList_CheckedChanged(object sender, EventArgs e)
        {
            canDataViewEable = chkDataList.Checked;
           
        }

        unsafe void bgw_rec_DoWork(object sender, DoWorkEventArgs e)
        {
            while (m_bOpen == 1)
            {
                UInt32 res = new UInt32();
                res = VCI_GetReceiveNum(m_devtype, m_devind, m_canind);
                if (res == 0)
                    continue;
                fixed (VCI_CAN_OBJ* pobj = &m_recobj[0])
                {
                    res = VCI_Receive(m_devtype, m_devind, m_canind, pobj, 50/*50*/, 50);
                }

                String str = "";
                for (UInt32 i = 0; i < res; i++)
                {
                    string canid = System.Convert.ToString((Int32)m_recobj[i].ID, 16);


                    string endtagstr = canid.Substring(canid.Length - 2, 2);
                    int stageIndex = Convert.ToInt32(endtagstr, 16) - 100;
                    int rowindex = stageIndex % 4;
                    if (rowindex == 0)
                    {
                        rowindex = 4;
                    }
                    rowindex = 5 - rowindex;
                    int colindex = ((stageIndex - 1) / 4) + 1;


                    str = "接收到数据: ";
                    str += "  帧ID:0x" + canid;

                    if (m_recobj[i].RemoteFlag == 0)
                    {
                        str += " 数据: ";
                        byte len = (byte)(m_recobj[i].DataLen % 9);
                        byte j = 0;

                        byte[] tempdata = new byte[8];
                        fixed (byte* bdata = m_recobj[i].Data)
                        {
                            if (j++ < len)
                                str += " " + System.Convert.ToString(bdata[0], 16);
                            tempdata[0] = bdata[0];
                            if (j++ < len)
                                str += " " + System.Convert.ToString(bdata[1], 16);
                            tempdata[1] = bdata[1];

                            if (tempdata[1] != 0x18)
                            {
                                continue;
                            }

                            if (j++ < len)
                                str += " " + System.Convert.ToString(bdata[2], 16);
                            tempdata[3] = bdata[2];
                            if (j++ < len)
                                str += " " + System.Convert.ToString(bdata[3], 16);
                            tempdata[2] = bdata[3];
                            if (j++ < len)
                                str += " " + System.Convert.ToString(bdata[4], 16);
                            tempdata[5] = bdata[4];
                            if (j++ < len)
                                str += " " + System.Convert.ToString(bdata[5], 16);
                            tempdata[4] = bdata[5];
                            if (j++ < len)
                                str += " " + System.Convert.ToString(bdata[6], 16);
                            tempdata[7] = bdata[6];
                            if (j++ < len)
                                str += " " + System.Convert.ToString(bdata[7], 16);
                            tempdata[6] = bdata[7];

                            int packindex = Convert.ToInt32(tempdata[0]);
                            if (packindex <= 5 || packindex >= 15)
                            {
                                continue;
                            }

                            Int16 tempint1 = BitConverter.ToInt16(tempdata, 2);
                            Int16 tempint2 = BitConverter.ToInt16(tempdata, 4);
                            Int16 tempint3 = BitConverter.ToInt16(tempdata, 6);

                            //更新全局温度list
                            //截取温度1，温度2，温度3
                            Byte[] temp1 = new Byte[] { tempdata[0], tempdata[1] };
                            Byte[] temp2 = new Byte[] { tempdata[2], tempdata[3] };
                            Byte[] temp3 = new Byte[] { tempdata[4], tempdata[5] };
                            SetTempData(1, colindex, rowindex, PackCHIdToChId((packindex * 3 - 2)), temp1);
                            SetTempData(1, colindex, rowindex, PackCHIdToChId((packindex * 3 - 1)), temp2);
                            SetTempData(1, colindex, rowindex, PackCHIdToChId((packindex * 3)), temp3);

                            //tempVal = Convert.ToString(Convert.ToDecimal(BitConverter.ToInt16(tempdata, 2)) * (decimal)0.1);
                            if (canDataViewEable)
                            {
                                str += " 架台：" + colindex.ToString() + "-" + rowindex.ToString();
                                str += " 温度值：" + (packindex * 3 - 2).ToString() + "(" + PackCHIdToChId((packindex * 3 - 2)) + ") : " + Convert.ToString(Convert.ToDecimal(tempint1) * (decimal)0.1);
                                str += " " + (packindex * 3 - 1).ToString() + "(" + PackCHIdToChId((packindex * 3 - 1)) + ") : " + Convert.ToString(Convert.ToDecimal(tempint2) * (decimal)0.1);
                                str += " " + (packindex * 3).ToString() + "(" + PackCHIdToChId((packindex * 3)) + ") : " + Convert.ToString(Convert.ToDecimal(tempint3) * (decimal)0.1);
                            }
                        }
                    }
                    if (canDataViewEable)
                    {
                        this.Invoke(new Action(() =>
                        {
                            listBox_Info.Items.Add(str);
                            listBox_Info.SelectedIndex = listBox_Info.Items.Count - 1;
                        }
                                             ));
                    }
                    Thread.Sleep(1);
                }
            }
        }

        unsafe void bgw_rec2_DoWork(object sender, DoWorkEventArgs e)
        {
            while (m_bOpen2 == 1)
            {
                UInt32 res = new UInt32();
                res = VCI_GetReceiveNum(m_devtype, m_devind2, m_canind);
                if (res == 0)
                    continue;

                //res = VCI_Receive(m_devtype, m_devind, m_canind, ref m_recobj[0],/*50*/1, 100);
                fixed (VCI_CAN_OBJ* pobj = &m_recobj2[0])
                {
                    res = VCI_Receive(m_devtype, m_devind2, m_canind, pobj, 50/*50*/, 100);
                }

                String str = "";
                for (UInt32 i = 0; i < res; i++)
                {
                    string canid = System.Convert.ToString((Int32)m_recobj2[i].ID, 16);

                    string endtagstr = canid.Substring(canid.Length - 2, 2);
                    int stageIndex = Convert.ToInt32(endtagstr, 16) - 100 + 16;
                    int rowindex = stageIndex % 4;
                    if (rowindex == 0)
                    {
                        rowindex = 4;
                    }
                    int colindex = ((stageIndex - 1) / 4) + 1;

                    str = "接收到数据: ";
                    str += "  帧ID:0x" + canid;

                    string tempVal = "";

                    if (m_recobj2[i].RemoteFlag == 0)
                    {
                        str += " 数据: ";
                        byte len = (byte)(m_recobj2[i].DataLen % 9);
                        byte j = 0;

                        byte[] tempdata = new byte[8];
                        fixed (byte* bdata = m_recobj2[i].Data)
                        {
                            if (j++ < len)
                                str += " " + System.Convert.ToString(bdata[0], 16);
                            tempdata[0] = bdata[0];
                            if (j++ < len)
                                str += " " + System.Convert.ToString(bdata[1], 16);
                            tempdata[1] = bdata[1];
                            if (j++ < len)
                                str += " " + System.Convert.ToString(bdata[2], 16);
                            tempdata[3] = bdata[2];
                            if (j++ < len)
                                str += " " + System.Convert.ToString(bdata[3], 16);
                            tempdata[2] = bdata[3];
                            if (j++ < len)
                                str += " " + System.Convert.ToString(bdata[4], 16);
                            tempdata[5] = bdata[4];
                            if (j++ < len)
                                str += " " + System.Convert.ToString(bdata[5], 16);
                            tempdata[4] = bdata[5];
                            if (j++ < len)
                                str += " " + System.Convert.ToString(bdata[6], 16);
                            tempdata[7] = bdata[6];
                            if (j++ < len)
                                str += " " + System.Convert.ToString(bdata[7], 16);
                            tempdata[6] = bdata[7];

                            int packindex = Convert.ToInt32(tempdata[0]);
                            if (packindex <= 5 || packindex >= 14)
                            {
                                continue;
                            }

                            Int16 tempint1 = BitConverter.ToInt16(tempdata, 2);
                            Int16 tempint2 = BitConverter.ToInt16(tempdata, 4);
                            Int16 tempint3 = BitConverter.ToInt16(tempdata, 6);

                            //更新全局温度list
                            //截取温度1，温度2，温度3
                            Byte[] temp1 = new Byte[] { tempdata[0], tempdata[1] };
                            Byte[] temp2 = new Byte[] { tempdata[2], tempdata[3] };
                            Byte[] temp3 = new Byte[] { tempdata[4], tempdata[5] };
                            SetTempData(2, colindex, rowindex, PackCHIdToChId((packindex * 3 - 2)), temp1);
                            SetTempData(2, colindex, rowindex, PackCHIdToChId((packindex * 3 - 1)), temp2);
                            SetTempData(2, colindex, rowindex, PackCHIdToChId((packindex * 3)), temp3);

                            tempVal = Convert.ToString(Convert.ToDecimal(BitConverter.ToInt16(tempdata, 2)) * (decimal)0.1);
                            if (canDataViewEable)
                            {
                                str += " 架台：" + colindex.ToString() + "-" + rowindex.ToString();
                                str += " 温度值：" + (packindex * 3 - 2).ToString() + "(" + PackCHIdToChId((packindex * 3 - 2)) + ") : " + tempVal;
                                str += " " + (packindex * 3 - 1).ToString() + "(" + PackCHIdToChId((packindex * 3 - 1)) + ") : " + Convert.ToString(Convert.ToDecimal(BitConverter.ToInt16(tempdata, 4)) * (decimal)0.1);
                                str += " " + (packindex * 3).ToString() + "(" + PackCHIdToChId((packindex * 3)) + ") : " + Convert.ToString(Convert.ToDecimal(BitConverter.ToInt16(tempdata, 6)) * (decimal)0.1);
                            }
                        }
                    }
                    if (canDataViewEable)
                    {

                        listBox_Info.Items.Add(str);
                        listBox_Info.SelectedIndex = listBox_Info.Items.Count - 1;
                    }
                    Thread.Sleep(100);
                }
            }
        }

        private void buttonConnect3_Click(object sender, EventArgs e)
        {
            if (m_bOpen3 == 1)
            {
                VCI_CloseDevice(m_devtype, m_devind3);
                m_bOpen3 = 0;
            }
            else
            {
                uint srcport = 0;

                m_devtype = (UInt32)can.DEV_TYPE.VCI_CANETTCP;//


                m_devind3 = (UInt32)2;
                m_canind3 = 0;// (UInt32)comboBox_CANIndex.SelectedIndex;

                if (VCI_OpenDevice(m_devtype, m_devind3, srcport) == 0)
                {
                    MessageBox.Show("打开设备失败,请检查设备类型和设备索引号是否正确", "错误",
                            MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }

                //m_bOpen = 1;
                //VCI_INIT_CONFIG config = new VCI_INIT_CONFIG();
                //config.AccCode = System.Convert.ToUInt32("0x" + textBox_AccCode.Text, 16);
                //config.AccMask = System.Convert.ToUInt32("0x" + textBox_AccMask.Text, 16);
                //config.Timing0 = System.Convert.ToByte("0x" + textBox_Time0.Text, 16);
                //config.Timing1 = System.Convert.ToByte("0x" + textBox_Time1.Text, 16);
                //config.Filter = (Byte)comboBox_Filter.SelectedIndex;
                //config.Mode = (Byte)comboBox_Mode.SelectedIndex;
                //VCI_InitCAN(m_devtype, m_devind, m_canind, ref config);

                //////////////////////////////////////////////////////////////////////////

                //
                string pip = tbxIP3.Text;
                char[] chars = pip.ToCharArray();
                byte[] bs = new byte[50];
                for (int i = 0; i < chars.Length; i++)
                {
                    bs[i] = (byte)chars[i];
                }
                uint cmdtype = (uint)can.CMD.CMD_DESIP;
                if ((uint)can.STATUS.STATUS_OK != VCI_SetReference(m_devtype, m_devind3, m_canind3, cmdtype, ref bs[0]))
                {
                    MessageBox.Show("设置目标IP出错 failed");
                    return;
                }
                //
                uint desport = Convert.ToUInt32(textBox_desport3.Text);
                byte[] desports = IntToBytes(desport, 4);
                cmdtype = (uint)can.CMD.CMD_DESPORT;
                if ((uint)can.STATUS.STATUS_OK != VCI_SetReference(m_devtype, m_devind3, m_canind3, cmdtype, ref desports[0]))
                {
                    MessageBox.Show("设置目标端口出错 failed");
                    return;
                }
                //

                cmdtype = (uint)can.CMD.CMD_TCP_TYPE;
                uint tcptype = (uint)can.TCPTYPE.TCP_CLIENT;
                byte[] types = IntToBytes(tcptype, 4);
                if ((uint)can.STATUS.STATUS_OK != VCI_SetReference(m_devtype, m_devind3, m_canind3, cmdtype, ref types[0]))
                {
                    MessageBox.Show("设置TCP工作方式出错 failed");
                    return;
                }



                m_bOpen3 = 1;
            }
            buttonConnect3.Text = m_bOpen3 == 1 ? "断开" : "连接";
            timer_rec3.Enabled = m_bOpen3 == 1 ? true : false;
        }

        private void button_StartCAN3_Click(object sender, EventArgs e)
        {
            if (m_bOpen3 == 0)
                return;
            if (1 != VCI_StartCAN(m_devtype, m_devind3, m_canind3))
            {
                MessageBox.Show("CAN-3启动失败", "错误", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            listBox_Info.Items.Add("CAN-3启动成功");
            listBox_Info.SelectedIndex = listBox_Info.Items.Count - 1;
        }

        private void button_StopCAN3_Click(object sender, EventArgs e)
        {
            if (m_bOpen3 == 0)
                return;
            VCI_ResetCAN(m_devtype, m_devind3, m_canind3);
        }

        unsafe private void timer_rec3_Tick(object sender, EventArgs e)
        {
            Thread thd3 = new Thread(Can3RecFunc);
            thd3.Start();
        }

        private void bgInitialServer_DoWork(object sender, DoWorkEventArgs e)
        {
            
            //初始化3个CanTempList为 3e fe
            Byte[] headbyte = { 0xfe, 0xdc, 0x10, 0x00, 0x01, 0x00, 0x01, 0x00 };//PackHead


            for (int i = 0; i < 960; i++)
            {
                if (i >= 642)
                {
                    TempCanData.Can1Temp.Add(0x00);
                    TempCanData.Can1Temp.Add(0x00);
                    TempCanData.Can2Temp.Add(0x00);
                    TempCanData.Can2Temp.Add(0x00);
                    TempCanData.Can3Temp.Add(0x00);
                    TempCanData.Can3Temp.Add(0x00);
                    TempCanData.Can4Temp.Add(0x19);
                    TempCanData.Can4Temp.Add(0xfc);
                    TempCanData.Can5Temp.Add(0x19);
                    TempCanData.Can5Temp.Add(0xfc);
                }
                else
                {
                    if (i == 0)
                    {
                        for (int m = 0; m < headbyte.Length; m++)
                        {
                            if (m == 4)
                            {
                                TempCanData.Can1Temp.Add(0x01);
                                TempCanData.Can2Temp.Add(0x02);
                                TempCanData.Can3Temp.Add(0x03);
                                TempCanData.Can4Temp.Add(0x04);
                                TempCanData.Can5Temp.Add(0x05);

                            }
                            else
                            {
                                TempCanData.Can1Temp.Add(headbyte[m]);
                                TempCanData.Can2Temp.Add(headbyte[m]);
                                TempCanData.Can3Temp.Add(headbyte[m]);
                                TempCanData.Can4Temp.Add(headbyte[m]);
                                TempCanData.Can5Temp.Add(headbyte[m]);
                            }

                        }
                        TempCanData.Can1Temp.Add(0x64);
                        TempCanData.Can1Temp.Add(0x00);
                        TempCanData.Can2Temp.Add(0x64);
                        TempCanData.Can2Temp.Add(0x00);
                        TempCanData.Can3Temp.Add(0x64);
                        TempCanData.Can3Temp.Add(0x00);
                        TempCanData.Can4Temp.Add(0x19);
                        TempCanData.Can4Temp.Add(0xfc);
                        TempCanData.Can5Temp.Add(0x19);
                        TempCanData.Can5Temp.Add(0xfc);
                    }
                    else
                    {
                        TempCanData.Can1Temp.Add(0x64);
                        TempCanData.Can1Temp.Add(0x00);
                        TempCanData.Can2Temp.Add(0x64);
                        TempCanData.Can2Temp.Add(0x00);
                        TempCanData.Can3Temp.Add(0x64);
                        TempCanData.Can3Temp.Add(0x00);
                        TempCanData.Can4Temp.Add(0x19);
                        TempCanData.Can4Temp.Add(0xfc);
                        TempCanData.Can5Temp.Add(0x19);
                        TempCanData.Can5Temp.Add(0xfc);
                    }

                }

            }

            Readyte = new TcpReciveAndSend();
            
           
            
        }

       
        private void bglisten_DoWork(object sender, DoWorkEventArgs e)
        {


        }
        /// <summary>
        /// 设置温度list的index对应的温度
        /// </summary>
        /// <param name="canno">CanNo</param>
        /// <param name="colno">列号</param>
        /// <param name="rowno">层号</param>
        /// <param name="chno">通道号</param>
        /// <param name="tempdata">温度</param>
        private void SetTempData(int canno,int colno,int rowno,int chno,Byte[] tempdata)
        {
            try
            {
                if (chno <= 25)
                {
                    int startindex = 8;
                    int tempindex = 0;
                    //colno = colno % 4;
                    //rowno = rowno % 4;

                    if (colno % 4 == 0)
                    {
                        colno = 3;
                    }
                    else
                    {
                        colno = colno % 4;
                        colno = colno - 1;
                    }

                    if (rowno == 4)
                    {
                        rowno = 0;
                    }
                    else
                    {
                        rowno = 4-rowno ;
                    }

                    int tempchno = chno;
                    //int tempchno = NewSeq[chno];
                    //tempchno=NewSeq[chno];
                    if (tempchno == 1)
                    {
                        tempchno = 0;
                    }
                    else
                    {
                        tempchno = tempchno - 1;
                    }
                    //暂时不判断24通道问题
                    tempindex = startindex + colno * 320 + rowno * 80 + 30 + tempchno * 2;
                    switch (canno)
                    {

                        case 1:
                            TempCanData.Can1Temp[tempindex] = tempdata[1];
                            TempCanData.Can1Temp[tempindex + 1] = tempdata[0];
                            break;
                        case 2:
                            TempCanData.Can2Temp[tempindex] = tempdata[1];
                            TempCanData.Can2Temp[tempindex + 1] = tempdata[0];
                            break;
                        case 3:
                            TempCanData.Can3Temp[tempindex] = tempdata[1];
                            TempCanData.Can3Temp[tempindex + 1] = tempdata[0];
                            break;
                    }
                }

            }
            catch (Exception ex)
            {

                Log.SystemError.Add(ex.ToString());
            }
            
        }


        
        private void button1_Click(object sender, EventArgs e)
        {

        }

        private void bginitialservice_DoWork(object sender, DoWorkEventArgs e)
        {

        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            
        }


        /// <summary>
        /// 初始化OldCan对应StageSeq
        /// </summary>
        public void InitialOldCanSeqList()
        {
            //Can1ChSeqNo

            //chno01
            OldSeq.Add(1, 6);
            //chno02
            OldSeq.Add(2,5);
            //chno03
            OldSeq.Add(3,4);
            //chno04
            OldSeq.Add(4,3);
            //chno05
            OldSeq.Add(5,2);
            //chno06
            OldSeq.Add(6,1);
            //chno07
            OldSeq.Add(7,12);
            //chno08
            OldSeq.Add(8,11);
            //chno09
            OldSeq.Add(9,10);

            //环境温度1-3
            //chno10
            OldSeq.Add(10, 9);
            //chno11
            OldSeq.Add(11, 8);
            //chno12
            OldSeq.Add(12, 7);

            //chno13
            OldSeq.Add(13,18);
            //chno14
            OldSeq.Add(14,17);
            //chno15
            OldSeq.Add(15,16);
            //chno16
            OldSeq.Add(16,15);
            //chno17
            OldSeq.Add(17,14);
            //chno18
            OldSeq.Add(18,13);
            //chno19
            OldSeq.Add(19,24);
            //chno20
            OldSeq.Add(20,23);
            //chno21
            OldSeq.Add(21,22);
            //chno22
            //环境温度4-6
            OldSeq.Add(22, 21);
            //chno23
            OldSeq.Add(23, 20);
            //chno24
            OldSeq.Add(24, 19);



            ////chno19
            //can1chseq.Add(22);
            ////chno20
            //can1chseq.Add(23);
            ////chno21 
            //can1chseq.Add(24);
            ////chno22 此通道温度需要验证下，在24之后的某一位是此通道的温度
            //can1chseq.Add(25);
            ////chno23 
            //can1chseq.Add(16);
            ////chno24
            //can1chseq.Add(17);

        }
        /// <summary>
        /// 初始化Can对应通道关系
        /// </summary>
        public void InitialCanSeqList()
        {
            //SEC界面显示通道对应Pack通道。

            //chno01
            NewSeq.Add(1, 10);
            //chno02
            NewSeq.Add(2, 1);
            //chno03
            NewSeq.Add(3, 2);
            //chno04
            NewSeq.Add(4, 3);
            //chno05
            NewSeq.Add(5, 4);
            //chno06
            NewSeq.Add(6, 5);
            //chno07
            NewSeq.Add(7, 14);
            //chno08
            NewSeq.Add(8, 15);
            //chno09
            NewSeq.Add(9, 6);
            //chno10
            NewSeq.Add(19, 7);
            //chno11
            NewSeq.Add(20, 8);
            //chno12
            NewSeq.Add(21, 9);
            //chno13
            NewSeq.Add(10, 18);
            //chno14
            NewSeq.Add(11, 19);
            //chno15
            NewSeq.Add(12, 20);
            //chno16
            NewSeq.Add(13, 11);
            //chno17
            NewSeq.Add(14, 12);
            //chno18
            NewSeq.Add(15, 13);
            //chno19
            NewSeq.Add(16, 22);
            //chno20
            NewSeq.Add(17, 23);
            //chno21
            NewSeq.Add(18, 24);
            //chno22
            NewSeq.Add(22, 25);
            //chno23
            NewSeq.Add(23, 16);
            //chno24
            NewSeq.Add(24, 17);




            ////chno01
            //can1chseq.Add(10);
            ////chno02
            //can1chseq.Add(1);
            ////chno03
            //can1chseq.Add(2);
            ////chno04
            //can1chseq.Add(3);
            ////chno05
            //can1chseq.Add(4);
            ////chno06
            //can1chseq.Add(5);
            ////chno07
            //can1chseq.Add(14);
            ////chno08
            //can1chseq.Add(15);
            ////chno09
            //can1chseq.Add(6);
            ////chno10
            //can1chseq.Add(7);
            ////chno11
            //can1chseq.Add(8);
            ////chno12
            //can1chseq.Add(9);
            ////chno13
            //can1chseq.Add(18);
            ////chno14
            //can1chseq.Add(19);
            ////chno15
            //can1chseq.Add(20);
            ////chno16
            //can1chseq.Add(11);
            ////chno17
            //can1chseq.Add(12);
            ////chno18
            //can1chseq.Add(13);
            ////chno19
            //can1chseq.Add(22);
            ////chno20
            //can1chseq.Add(23);
            ////chno21 
            //can1chseq.Add(24);


            ////chno22 此通道温度需要验证下，在24之后的某一位是此通道的温度
            //can1chseq.Add(25);
            ////chno23 
            //can1chseq.Add(16);
            ////chno24
            //can1chseq.Add(17);

        }
        //PackCHIdToChId
        private void button1_Click_2(object sender, EventArgs e)
        {


            //int packindex = Convert.ToInt32(tbxchno.Text);
            //int chno1 = PackCHIdToChId((packindex * 3 - 2));
            //int chno2 = PackCHIdToChId((packindex * 3 - 1));
            //int chno3 = PackCHIdToChId((packindex * 3));

            //转换1-9通道顺序，10-12环境温度（1-3），13-21（通道顺序10-18），22-24（环境温度），除通道温度之外，其他温度全部舍弃。




            //chno1 = ResortChNo(chno1);
            //chno2 = ResortChNo(chno2);
            //chno3 = ResortChNo(chno3);

            //UpdateToPLC(colindex, rowindex, PackCHIdToChId((packindex * 3 - 2)), tempint1);

            //if (chno1 != 999)
            //{
            //    chno1 = can1chseq[chno1 - 1];
            //} else
            //{
            //    chno1 = 0;
            //}
            //if (chno2 != 999)
            //{
            //    chno2 = can1chseq[chno2 - 1];
            //}

            //if (chno3 != 999)
            //{
            //    chno3 = can1chseq[chno3 - 1];
            //}

            //tbxresult.Text = "chno:" + ResortChNo(packindex);
            //tbxresult.Text = "chno1:" + chno1 + ",chno2:" + chno2 + ",chno3:" + chno3;



            //31-34
            Byte[] can31 = new byte[] { 0x01, 0x36 };
            Byte[] can32 = new byte[] { 0x01, 0x40 };
            Byte[] can33 = new byte[] { 0x01, 0x4a };
            Byte[] can34 = new byte[] { 0x01, 0x54 };
            Byte[] can35 = new byte[] { 0x01, 0x5e };
            Byte[] can36 = new byte[] { 0x01, 0x68 };
            //41-44
            Byte[] can41 = new byte[] { 0x01, 0x9a };
            Byte[] can42 = new byte[] { 0x01, 0xa4 };
            Byte[] can43 = new byte[] { 0x01, 0xae };
            Byte[] can44 = new byte[] { 0x01, 0xb8 };
            Byte[] can45 = new byte[] { 0x01, 0xc2 };
            Byte[] can46 = new byte[] { 0x01, 0xcc };

            //51-54
            Byte[] can51 = new byte[] { 0x01, 0xfe };
            Byte[] can52 = new byte[] { 0x02, 0x08 };
            Byte[] can53 = new byte[] { 0x02, 0x12 };
            Byte[] can54 = new byte[] { 0x02, 0x1c };
            Byte[] can55 = new byte[] { 0x02, 0x26 };
            Byte[] can56 = new byte[] { 0x02, 0x30 };
            //
            for (int i = 1; i <= 4; i++)
            {
                for (int m = 1; m <= 4; m++)
                {
                    int tempno = 411;
                    int tempno1 = 511;
                    int tempno2 = 311;
                    for (int n = 1; n <= 24; n++)
                    {
                        byte[] chnotest = new byte[2];
                        byte[] bb = BitConverter.GetBytes((short)tempno);
                        chnotest[0] = bb[1];
                        chnotest[1] = bb[0];

                        byte[] chnotest1 = new byte[2];
                        byte[] bb1 = BitConverter.GetBytes((short)tempno1);
                        chnotest1[0] = bb1[1];
                        chnotest1[1] = bb1[0];

                        byte[] chnotest2 = new byte[2];
                        byte[] bb2 = BitConverter.GetBytes((short)tempno2);
                        chnotest2[0] = bb2[1];
                        chnotest2[1] = bb2[0];

                        if (i == 1)
                        {

                            SetTempData(1, i, m, NewSeq[n], chnotest2);
                            SetTempData(2, i, m, NewSeq[n], chnotest);
                            SetTempData(3, i, m, NewSeq[n], chnotest1);

                        }
                        else if (i == 2)
                        {

                            SetTempData(1, i, m, n, can31);
                            SetTempData(2, i, m, NewSeq[n], chnotest);
                            SetTempData(3, i, m, NewSeq[n], chnotest1);
                        }
                        else if (i == 3)
                        {
                            SetTempData(1, i, m, n, can31);
                            SetTempData(2, i, m, NewSeq[n], chnotest);
                            SetTempData(3, i, m, NewSeq[n], chnotest1);
                        }
                        else if (i == 4)
                        {
                            SetTempData(1, i, m, n, can31);
                            SetTempData(2, i, m, NewSeq[n], chnotest);
                            SetTempData(3, i, m, NewSeq[n], chnotest1);
                        }

                        tempno++;
                        tempno1++;
                        tempno2++;
                        //else if (i == 5)
                        //{
                        //    SetTempData(1, i, m, n, can35);
                        //    SetTempData(2, i, m, n, can45);
                        //    SetTempData(3, i, m, n, can55);
                        //}
                        //else if (i == 6)
                        //{
                        //    SetTempData(1, i, m, n, can36);
                        //    SetTempData(2, i, m, n, can46);
                        //    SetTempData(3, i, m, n, can56);
                        //}



                    }
                }
            }

            //////tbxchno.Text = ResortChNo(int.Parse(tbxchno.Text)).ToString();



        }

        private void bgwritelog_DoWork(object sender, DoWorkEventArgs e)
        {

        }

        private void bgWriteLog_DoWork(object sender, DoWorkEventArgs e)
        {
            
        }

        private void toolTip1_Popup(object sender, PopupEventArgs e)
        {

        }

        private void timerTempdataAdd_Tick(object sender, EventArgs e)
        {
            try
            {
                //Readyte.analysisBytes.TempCorrectingsndBytes.Add(TempCanData.Can1Temp.ToArray());
                //Readyte.analysisBytes.TempCorrectingsndBytes.Add(TempCanData.Can2Temp.ToArray());
                //Readyte.analysisBytes.TempCorrectingsndBytes.Add(TempCanData.Can3Temp.ToArray());
            }
            catch { }
        }

        private void label15_Click(object sender, EventArgs e)
        {
            //设置数据上传时间间隔
            FormDataShow show = new FormDataShow();
            show.Show();
        }

        private void textBox_srcport_TextChanged(object sender, EventArgs e)
        {
            
        }

        private void textBox_desport_TextChanged(object sender, EventArgs e)
        {

        }
    }





}

namespace can
{

    // 设备型号
    public enum DEV_TYPE
    {
        VCI_PCI5121 = 1,
        VCI_PCI9810 = 2,
        VCI_USBCAN1 = 3,
        VCI_USBCAN2 = 4,
        VCI_USBCAN2A = 4,
        VCI_PCI9820 = 5,
        VCI_CAN232 = 6,
        VCI_PCI5110 = 7,
        VCI_CANLITE = 8,
        VCI_ISA9620 = 9,
        VCI_ISA5420 = 10,
        VCI_PC104CAN = 11,
        VCI_CANETE = 12,
        VCI_DNP9810 = 13,
        VCI_PCI9840 = 14,
        VCI_PC104CAN2 = 15,
        VCI_PCI9820I = 16,
        VCI_PEC9920 = 18,
        VCI_CANETTCP = 17,
        VCI_PCI5010U = 19,
        VCI_USBCANEU = 20,
        VCI_USBCAN2EU = 21,
    };

    // CAN错误码
    public enum CAN_ERR
    {
        ERR_CAN_OVERFLOW = 0x0001, //CAN控制器内部FIFO溢出
        ERR_CAN_ERRALARM = 0x0002, //CAN控制器错误报警
        ERR_CAN_PASSIVE = 0x0004, //CAN控制器消极错误
        ERR_CAN_LOSE = 0x0008, //CAN控制器仲裁丢失
        ERR_CAN_BUSERR = 0x0010, //CAN控制器总线错误
        ERR_CAN_BUSCLOSE = 0x0020, //CAN控制器总线关闭
    };

    // 通用错误码
    public enum DEV_ERR
    {
        ERR_DEVICEOPENED = 0x0100, //设备已经打开
        ERR_DEVICEOPEN = 0x0200, //打开设备错误
        ERR_DEVICENOTOPEN = 0x0400, //设备没有打开
        ERR_BUFFEROVERFLOW = 0x0800, //缓冲区溢出
        ERR_DEVICENOTEXIST = 0x1000, //此设备不存在
        ERR_LOADKERNELDLL = 0x2000, //装载动态库失败
        ERR_CMDFAILED = 0x4000, //执行命令失败错误码
        ERR_BUFFERCREATE = 0x8000, //内存不足
    };

    // 函数调用返回状态值
    public enum STATUS
    {
        STATUS_OK = 1,
        STATUS_ERR = 0,
    };

    // 函数调用返回状态值
    public enum CMD
    {
        CMD_DESIP = 0,
        CMD_DESPORT = 1,
        CMD_SRCPORT=2,
        CMD_CHGDESIPANDPORT = 2,
        CMD_TCP_TYPE = 4,//tcp 工作方式，服务器:1 或是客户端:0
    };

    public enum TCPTYPE
    {
        TCP_CLIENT = 0,
        TCP_SERVER = 1,
    }

    public enum REF
    {
        REFERENCE_BAUD = 1,
        REFERENCE_SET_TRANSMIT_TIMEOUT = 2,
        REFERENCE_ADD_FILTER = 3,
        REFERENCE_SET_FILTER = 4,
    };
}

//1.ZLGCAN系列接口卡信息的数据类型。
public struct VCI_BOARD_INFO
{
    public UInt16 hw_Version;
    public UInt16 fw_Version;
    public UInt16 dr_Version;
    public UInt16 in_Version;
    public UInt16 irq_Num;
    public byte can_Num;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 20)]
    public byte[] str_Serial_Num;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 40)]
    public byte[] str_hw_Type;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
    public byte[] Reserved;
}

//2.定义CAN信息帧的数据类型。
//public struct VCI_CAN_OBJ
//{
//    public UInt32 ID;
//    public UInt32 TimeStamp;
//    public byte TimeFlag;
//    public byte SendType;
//    public byte RemoteFlag;//是否是远程帧
//    public byte ExternFlag;//是否是扩展帧
//    public byte DataLen;
//    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
//    public byte[] Data;
//    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
//    public byte[] Reserved;


//    public void Init()
//    {
//        Data = new byte[8];
//        Reserved = new byte[3];
//    }
//}
//2.定义CAN信息帧的数据类型。
unsafe public struct VCI_CAN_OBJ  //使用不安全代码
{
    public uint ID;
    public uint TimeStamp;
    public byte TimeFlag;
    public byte SendType;
    public byte RemoteFlag;//是否是远程帧
    public byte ExternFlag;//是否是扩展帧
    public byte DataLen;

    public fixed byte Data[8];

    public fixed byte Reserved[3];


    public void Init()
    {
        //Data = new byte[8];
        //Reserved = new byte[3];
    }
}

//3.定义CAN控制器状态的数据类型。
public struct VCI_CAN_STATUS
{
    public byte ErrInterrupt;
    public byte regMode;
    public byte regStatus;
    public byte regALCapture;
    public byte regECCapture;
    public byte regEWLimit;
    public byte regRECounter;
    public byte regTECounter;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
    public byte[] Reserved;
}

//4.定义错误信息的数据类型。
public struct VCI_ERR_INFO
{
    public UInt32 ErrCode;
    public byte Passive_ErrData1;
    public byte Passive_ErrData2;
    public byte Passive_ErrData3;
    public byte ArLost_ErrData;
}

//5.定义初始化CAN的数据类型
public struct VCI_INIT_CONFIG
{
    public UInt32 AccCode;
    public UInt32 AccMask;
    public UInt32 Reserved;
    public byte Filter;
    public byte Timing0;
    public byte Timing1;
    public byte Mode;
}

public struct CHGDESIPANDPORT
{
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)]
    public byte[] szpwd;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 20)]
    public byte[] szdesip;
    public Int32 desport;

    public void Init()
    {
        szpwd = new byte[10];
        szdesip = new byte[20];
    }
}